package com.robot.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.robot.web.constant.APIConstant;
import com.robot.web.constant.MessageConstant;
import com.robot.web.dto.UserDTO;
import com.robot.web.service.LoginService;

@Controller
public class HomeController extends BaseController {

	@Autowired
	private LoginService loginServiceImpl;

	@RequestMapping(value = "/login")
	public String login(ModelMap modelMap, UserDTO user) {
		return "login";
	}

	@RequestMapping(value = "/loginSubmit")
	@ResponseBody
	public Map<String, Object> loginSubmit(HttpServletRequest request, HttpServletResponse respone, UserDTO user) {
		logger.debug("user" + user);
		
		Map<String, Object> result= this.restTemplate.postForObject(APIConstant.SERVICE_LOGIN, user, ModelMap.class);
		
		// Can get Role or Full name here
		
		if ("Success".equalsIgnoreCase( (String)result.get("loginstatus")) ) {
			request.getSession(true).setAttribute(MessageConstant.COMMON_AUTHORISED, MessageConstant.COMMON_AUTHORISED);
			request.getSession(true).setAttribute("USERNAME", user.getUsername());
		}
		
		return result;
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request, HttpServletResponse respone, UserDTO user) {

		logger.debug("logout..."+user);
		HttpSession session = request.getSession(false);  
        if (session != null) {  
            session.invalidate();  
        }  

		return "/login";
	}

	@RequestMapping(value = "/desktop", method = RequestMethod.GET)
	public String desktop(ModelMap modelMap) {
		return "desktop";
	}

}
